package com.heiyu.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author：puremancw
 * @Description：邀请码工具类
 * @Date：Create in 11:49 2017/10/19
 * @Modified by：
 */
public class InviteCodeUtil {

    private static String key = "trip";
    private static char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f' };
    private static String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g",
            "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6",
            "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
            "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
            "x", "y", "z" };

    public static String generateShortInviteCode(String code) {

        String sMD5EncryptResult = getMd5(key+code);
        String hex = sMD5EncryptResult;
        String resUrl = null;
        String sTempSubString = hex.substring(8, 16);
        System.out.println(sTempSubString);
        long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
        String outChars = "";
        for (int j = 0; j < 6; j++) {
            long index = 0x0000003D & lHexLong;
            outChars += chars[(int) index];
            lHexLong = lHexLong >> 5;
        }
        resUrl = outChars;
        return resUrl;
    }

    public static String getMd5(String s) {
        byte[] b = s.getBytes();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(b);
            byte[] b2 = md.digest();
            char str[] = new char[b2.length << 1];
            int len = 0;
            for (int i = 0; i < b2.length; i++) {
                byte val = b2[i];
                str[len++] = hexChar[(val >>> 4) & 0xf];
                str[len++] = hexChar[val & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
